package com.wydexcel.generate.process;

import com.wydexcel.generate.properties.s.ExcelFontProperties;
import com.wydexcel.generate.properties.s.ExcelRichTextCollectionProperties;
import com.wydexcel.generate.properties.s.ExcelRichTextProperties;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

public class WydExcelRichTextProcessImpl implements WydExcelRichTextProcess {

    private WydExcelCellFontProcessImpl fontProcess = new WydExcelCellFontProcessImpl();

    @Override
    public XSSFRichTextString richTextProcess(Row row, Cell cell, Sheet sheetAt, ExcelRichTextCollectionProperties properties, boolean isBody) {

        if (null == properties) {
            return null;
        }
        if (isBody) {
            if (properties.getIsHeader() == 1) {
                return null;
            }
        } else {
            if (properties.getIsHeader() == 2) {
                return null;
            }
        }


        if (null == properties.getFieldName() || "".equals(properties.getFieldName())) {
            return null;
        }

        XSSFRichTextString rt = new XSSFRichTextString(properties.getText());
        for (ExcelRichTextProperties richTextProperties : properties.getRichTextProperties()) {
            ExcelFontProperties fontProperties = richTextProperties.getFont();
            if (null != fontProperties) {
                fontProperties.setFieldName(properties.getFieldName() + "_rich_" + fontProperties.hashCode() + isBody);
                XSSFFont font = (XSSFFont) fontProcess.fontProcess(row, cell, fontProperties, fontProperties.getFieldName(), isBody);
                if (null != font) {
                    if (null != richTextProperties.getStartIndex() && null != richTextProperties.getEndIndex()) {
                        rt.applyFont(richTextProperties.getStartIndex(), richTextProperties.getEndIndex(), font);
                    }else {
                        rt.applyFont(font);
                    }
                }
            }

        }

        return rt;
    }
}